#!/bin/bash

# enable_passwordless_sudo.sh
# 功能说明:
# 1. 检查用户是否在 sudo 组，如果不在则添加。
# 2. 为一个或多个用户启用免密码 sudo 权限。
# 3. 支持通过命令行参数传入用户名列表，如果未传入参数，则默认操作当前用户。
# 4. 自动检测用户是否已经具有免密码 sudo 权限，避免重复配置。
# 5. 输出每个用户的配置结果，包括成功或已启用的状态。
# 6. 限制脚本只能由非 root 用户执行。

enable_passwordless_sudo() {
  local user="$1"

  echo "Configuring sudo for user: $user"

  # 检查用户是否在 sudo 组
  if ! id -nG "$user" | grep -qw "sudo"; then
    echo "User $user is not in the sudo group. Adding to sudo group..."
    sudo usermod -aG sudo "$user"
    echo "User $user has been added to the sudo group."
  else
    echo "User $user is already in the sudo group."
  fi

  # 检查 /etc/sudoers 是否已配置免密码 sudo
  if sudo grep -q "$user ALL=(ALL) NOPASSWD: ALL" /etc/sudoers; then
    echo "Passwordless sudo is already enabled for $user."
  else
    echo "Enabling passwordless sudo for user: $user"
    echo "$user ALL=(ALL) NOPASSWD: ALL" | sudo bash -c '(EDITOR="tee -a" visudo)'
    echo "Passwordless sudo has been enabled for $user."
  fi
}

main() {
  # 确保脚本由非 root 用户执行
  if [[ $EUID -eq 0 ]]; then
    echo "This script must be run as a non-root user."
    exit 1
  fi

  # 如果没有提供用户名，则默认操作当前用户
  if [[ $# -eq 0 ]]; then
    echo "No usernames provided. Defaulting to the current user: $USER"
    enable_passwordless_sudo "$USER"
  else
    # 遍历所有传入的用户名
    for user in "$@"; do
      if id "$user" &>/dev/null; then
        enable_passwordless_sudo "$user"
      else
        echo "User $user does not exist on this system."
      fi
    done
  fi
}

# 执行主函数
main "$@"

